package com.atguigu.demotest;

import jdk.nashorn.internal.ir.CallNode;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author sunjipu
 * @create 2020-03-27 9:10
 */
class Ticket{
    private int number=50;
    private Lock lock=new ReentrantLock();

    public void sale(){
        lock.lock();
        try {
            if (number>0)
            {
                System.out.println(Thread.currentThread().getName()+"\t卖出第："+(number--)+"\t 还剩下："+number);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }

}
public class DemoShop {
    public static void main(String[] args) {
        Ticket ticket=new Ticket();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i <55; i++) {
//                    ticket.sale();
//                }
//            }
//        },"A").start();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i <55; i++) {
//                    ticket.sale();
//                }
//            }
//        },"B").start();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i <55; i++) {
//                    ticket.sale();
//                }
//            }
//        },"C").start();

        ExecutorService threadPool= Executors.newFixedThreadPool(3);
        try {

            for (int i = 0; i <55; i++) {
                threadPool.submit(()->{
                    ticket.sale();
                });
        }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}
